import { PaginatorPlugin } from "@datorama/akita";
import { switchMap, tap } from "rxjs/operators";

import { RoomsQuery, RoomsStore, makeStore, RoomEntity } from "@/state/roomEntity/store";
import roomService from "@/services/roomService";
import { ROOMSTATS_TYPE } from "@/constants/room";

export class RoomsFacade {
  constructor(private statType: number, private store: RoomsStore, private query: RoomsQuery, public paginator: PaginatorPlugin<RoomEntity>) { }
  readonly filter$ = this.query.filter$;

  pagination$ = this.paginator.pageChanges.pipe(
    switchMap((pageNum) => {
      let reqFn;
      switch (this.statType) {
        case ROOMSTATS_TYPE.CREATED:
          {
            reqFn = () => roomService.getCreatedRoomSvc(pageNum, 10);
            break;
          }
        case ROOMSTATS_TYPE.STARTING:
          {
            reqFn = () => roomService.getStartingRoomSvc(pageNum, 10);
            break;
          }
        case ROOMSTATS_TYPE.VISITED:
        default:
          {
            reqFn = () => roomService.getWatchedRoomSvc(pageNum, 10);
            break;
          }
      }
      return this.paginator.getPage(reqFn);
    }),
    tap(console.log)
  )

  prevPage = () => {
    this.paginator.prevPage();
  }

  nextPage = () => {
    this.paginator.nextPage();
  }

  //销毁store实例，释放内存
  destroy = () => {
    this.paginator.destroy();
    this.store.destroy();
  }
}

export const makeFacade = (statType: number): RoomsFacade => {
  const [store, query, rooms_paginator] = makeStore();

  return new RoomsFacade(statType, store, query, rooms_paginator);
}